package com.cameron.serviceedu.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cameron.serviceedu.entity.EduSubject;
import com.cameron.serviceedu.entity.excel.SubjectData;
import com.cameron.servicebase.config.exception.BusinessException;
import com.cameron.serviceedu.service.EduSubjectService;

import static com.cameron.constant.CourseConstant.PARENT_ID;


/**
 * @author Mind
 * 对象监听器
 */
public class SubjectListener extends AnalysisEventListener<SubjectData> {

    public EduSubjectService eduSubjectService;

    public SubjectListener() {
    }

    public SubjectListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null) {
            throw new BusinessException(20001,"文件数据为空！");
        }
        //判断该一级分类是否已经存在数据库中
        if (this.existSubjectOne(subjectData.getSubjectNameOne()) == null){
            //若不存在将数据存入数据库中
            EduSubject subject = new EduSubject();
            subject.setParentId(PARENT_ID);
            subject.setTitle(subjectData.getSubjectNameOne());
            eduSubjectService.save(subject);
        }
        //获取父分类的id
        String parentId = this.existSubjectOne(subjectData.getSubjectNameOne()).getId();
        //判断该二级分类是否已在数据库中
        if (this.existSubjectTwo(subjectData.getSubjectNameTwo(),parentId) == null) {
            EduSubject subject = new EduSubject();
            subject.setParentId(parentId);
            subject.setTitle(subjectData.getSubjectNameTwo());
            eduSubjectService.save(subject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    //判断一级分类不能重复添加
    private EduSubject existSubjectOne(String name){
        LambdaQueryWrapper<EduSubject> lqw = new LambdaQueryWrapper<>();
        lqw.eq(EduSubject::getTitle,name)
                .eq(EduSubject::getParentId,'0');
        return eduSubjectService.getOne(lqw);
    }

    //判断二级分类不能重复添加
    private EduSubject existSubjectTwo(String name,String parentId){
        LambdaQueryWrapper<EduSubject> lqw = new LambdaQueryWrapper<>();
        lqw.eq(EduSubject::getTitle,name)
                .eq(EduSubject::getParentId,parentId);
        return eduSubjectService.getOne(lqw);
    }
}
